package com.imooc.coupon.executor.impl;

import com.imooc.coupon.executor.AbstractRuleExecutor;
import com.imooc.coupon.support.vo.CouponTemplateSDK;
import com.imooc.coupon.support.vo.SettlementInfo;
import com.imooc.coupon.support.vo.TemplateRule;
import com.imooc.coupon.constant.RuleFlag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collections;

/**
 * 优惠券满减规则结算执行器
 *
 * Created By TINY
 * Create Time 2020/2/12
 **/
@Slf4j
@Component
public class FullReductionExecutor extends AbstractRuleExecutor {

    /**
     * 优惠券结算规则类型标记
     *
     * @return {@link RuleFlag} 优惠券结算规则标记
     */
    @Override
    public RuleFlag supports() {
        return RuleFlag.FULL_REDUCTION;
    }

    /**
     * 核心的满减优惠券规则计算逻辑实现
     *
     * @param settlementInfo {@link SettlementInfo} 结算信息对象
     * @return {@link SettlementInfo} 计算处理后的结算信息对象
     */
    @Override
    protected SettlementInfo cProcess(SettlementInfo settlementInfo) {
        CouponTemplateSDK templateSDK = settlementInfo
                .getCouponAndTemplateInfos().get(0).getTemplate();

        TemplateRule.Discount discount = templateSDK.getRule().getDiscount();
        // 获取优惠券折扣基准值
        double base = (double) discount.getBase();

        // 获取优惠券折扣额度（满足折扣基准后可用）
        double quota = (double) discount.getQuota();

        // 获取商品原始总价
        double goodsOriginalCost = settlementInfo.getCost();

        // 如果商品总价没有达到折扣基准值，则返回商品总价并清空优惠券列表
        if (goodsOriginalCost < base) {
            log.warn("商品总价没有达到满减基准值，无法使用优惠券！");
            settlementInfo.setCost(goodsOriginalCost); // 设置商品原始总价
            settlementInfo.setCouponAndTemplateInfos(
                    Collections.emptyList());          // 清空优惠券列表

            return settlementInfo;
        }

        // 商品总价达到了折扣基准值，计算折扣
        settlementInfo.setCost(
                retain2Decimals((goodsOriginalCost - quota) > minCost()
                        ? (goodsOriginalCost - quota) : minCost()
                ));

        return settlementInfo;
    }
}
